<?php
namespace app\index\controller;
use app\model\User as UserModel;
use app\model\UserToken as UserTokenModel;

use think\facade\Cache;
use think\captcha\Captcha;

use think\Db;


class User extends Base
{   

    protected $noCheckToken = ['register','login','getSmsCaptcha','getEmailCaptcha','forget','smsLogin'];

    // 手机验证码
    public function getSmsCaptcha($mobile){
        $code = rand(1000,9999);
        $sms_status = sendSms($mobile,'您的验证码是：'.$code,'得力云');

        if ($sms_status['status'] == 1) {
            Cache::set($mobile, $code, 120);
            // Db::name('test')->insert(['content'=>'sms:'.$code]);
            return apiResult('2000','发送成功');
        }else{
            return apiResult('5000',$sms_status['msg']);
        }
    }

    /**
     * 登录
     * @Author   cch
     * @DateTime 2020-05-29T12:06:40+0800
     * @param    $mobile   [description]
     * @param    $verify   验证码
     * @return             [description]
     */
    public function login(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        
        $fields = [
            'must'=>['mobile','password'],
            'nomust'=>[]
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $model = new UserModel();
        $data = $model->where('mobile',$params['mobile'])->find();
        if ( empty($data) ) {
            return apiResult('5000','账号不存在');
        }
        if ( $data['password'] != md5($params['password']) ) {
            return apiResult('5000','密码错误');
        }

        Db::startTrans();
        try{
            // 生成token
            $token_data = [
                'user_id'=>$data['id'],
                'access_token'=>uuidCreate(),
                'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                'utype'=>0
            ];
            UserTokenModel::where('user_id',$token_data['user_id'])->delete();
            if ( !UserTokenModel::insert($token_data) ) {
                throw new \Exception("token生成失败");
            }

            // 记录最后登录时间
            $model->where('id',$data['id'])->update(['login_time'=>time()]);
            Db::commit();
            return apiResult('2000','登录成功',$token_data);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    /**
     * 登录
     * @Author   cch
     * @DateTime 2020-05-29T12:06:40+0800
     * @param    $mobile   [description]
     * @param    $verify   验证码
     * @return             [description]
     */
    public function smsLogin(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        
        $fields = [
            'must'=>['mobile','verify'],
            'nomust'=>[]
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $code = Cache::get($params['mobile'], '');
        // dump($code);die;
        $model = new UserModel();
        $data = $model->where('mobile',$params['mobile'])->find();
        if ( empty($data) ) {
            return apiResult('5000','账号不存在');
        }
        if ( $code != $params['verify'] ) {
            return apiResult('5000','验证码错误');
        }

        Db::startTrans();
        try{
            // 生成token
            $token_data = [
                'user_id'=>$data['id'],
                'access_token'=>uuidCreate(),
                'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                'utype'=>0
            ];
            UserTokenModel::where('user_id',$token_data['user_id'])->delete();
            if ( !UserTokenModel::insert($token_data) ) {
                throw new \Exception("token生成失败");
            }

            Cache::set($params['mobile'], ''); // 清除验证码

            // 记录最后登录时间
            $model->where('id',$data['id'])->update(['login_time'=>time()]);
            Db::commit();
            return apiResult('2000','登录成功',$token_data);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }


    // 详情
    public function read(){
        $ulogin = $this->login_user;
        if ($ulogin['utype'] == 1) {
            $data = Db::name('ram')->field(['password'],true)->where('id',$ulogin['ram_id'])->find();
        }else{
            $data = Db::name('user')->field(['password'],true)->where('id',$ulogin['user_id'])->find();
        }
        $data['utype'] = $ulogin['utype'];
        
        return apiResult('2000','获取成功',$data);
    }


    // 邮箱验证码
    public function getEmailCaptcha($email){
        $code = rand(1000,9999);
        
        // $code = '123456';
        $sms_status = sendMail($email,'聚泽居','邮箱验证码','您的验证码是：'.$code);

        if ( $sms_status ) {
            Cache::set($email, $code, 120);
            Db::name('test')->insert(['content'=>'email:'.$code]);
            return apiResult('2000','发送成功');
        }else{
            return apiResult('5000',$sms_status['msg']);
        }
    }

    // 注册
    public function register(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        
        $fields = [
            'must'=>['truename','nickname','password','verify'],
            'nomust'=>['mobile','email','area_code','source']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            exception($save_data['error_msg'],400);
        }

        $account = $save_data['mobile'];
        if ( empty($account) ) {
            $account = $save_data['email'];
        }
        if ( empty($account) ) {
            return apiResult('5000','邮箱/手机至少需要有一个');
        }

        $code = Cache::get($account, '');
        $verify = $save_data['verify'];
        unset($save_data['verify']);
        if( empty($code) || $code != $verify ){
            return apiResult('5000','验证码错误');
        }

        $model = new UserModel();
        if ( !empty($model->where('email|mobile',$account)->value('uuid')) ) {
            return apiResult('5000','当前手机/邮箱已被占用');
        }

        $save_data['uuid'] = uuidCreate();
        $save_data['create_time'] = date('Y-m-d H:i:s');
        $save_data['password'] = md5($save_data['password']);

        if ( $model->insert($save_data) ) {
            Cache::set($account, null);
            return apiResult('2000','注册成功',$save_data['uuid']);
        }else{
            return apiResult('5000','注册异常');
        }
    }

    


    // 更新
    public function update(){
        $model = new UserModel();
        $uuid = $this->login_user['uuid'];

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        // 'mobile','email',
        $fields = [
            'nomust'=>['truename','password','headimgurl','nickname','remark','sex','province','city','area','whats_app','area_code','notice_type','mobile','email']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
        if (empty($save_data)) {
            return apiResult('5000','无任何修改');
        }
        if (!empty($save_data['mobile']) && $model->where([
            ['uuid','<>',$uuid],
            ['mobile','=',$save_data['mobile']]
        ])->count() > 0) {
            return apiResult('5000','手机号已被占用');
        }
        if (!empty($save_data['email']) && $model->where([
            ['uuid','<>',$uuid],
            ['email','=',$save_data['email']]
        ])->count() > 0) {
            return apiResult('5000','邮箱已被占用');
        }

        
        // 启动事务 
        Db::startTrans();
        try{
            if (!empty($save_data['password'])) {
                $save_data['password'] = md5($save_data['password']);
            }
            if ( $model->where('uuid',$uuid)->update($save_data) === false ) {
                throw new \Exception("保存失败");
            }
            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','更新成功');
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

   

}
